package com.apexedu.portal.service.impl;

import com.apexedu.framework.util.DBUtil;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 用户登录处理类。包括系统管理员也集成在此登录。
 * 
 * @author Yangjianliang datetime 2011-2-26
 */
@SuppressWarnings("serial")
public class AjaxSearch extends HttpServlet {

	private static Log LOG = LogFactory.getLog(AjaxSearch.class);

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		executeAction(request, response, false);
	}

	/**
	 * 和post的区别就是参数需要解码，以支持中文昵称登录
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		executeAction(request, response, true);
	}
	
	private static void executeAction(HttpServletRequest request, HttpServletResponse response, boolean needDecode) throws IOException{
		request.setCharacterEncoding("UTF-8");//处理post中文问题
		TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		Map<String, Object> outData = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		String condition = request.getParameter("conditions");
		String gjz=request.getParameter("gjz");
		String path=request.getParameter("path");
		String conditions[]=condition.split(",");
		Random rand =new Random();
		String sql_serach=" select t.*,nvl(s.unit,'暂无') as unit,nvl(s.workingtime,'暂无') as workingtime,nvl(s.workingplace,'暂无') as workingplace," +
						  " nvl(s.contact,'暂无') as contact,s.rulesintroduced,s.attention," +
						  " nvl((select c.zdmc from T_SYS_CODE c where c.zdbm=s.version and zdlb='version' ),'暂无') as version, " +
						  " to_char((select wm_concat(c.zdmc) from t_service_code c where c.zdbm in (select m.serviceid from t_service_menu m where m.menuid=t.menuid) and c.zdlb='fwlb' )) as fwtype," +
						  " to_char((select nvl(avg(satisfaction),3) as satisfaction from T_Service_Satisfaction where menuid=t.menuid )) as score "+
						  " from t_sys_menu t " +
						  " left join T_SERVICE_INTRODUCD s on s.menuid=t.menuid" +
				          " where exists (select 1 from t_service_menu m where m.menuid=t.menuid) and t.state='1'";
		String tj="";
		String px="";
		String pxfs="";
		StringBuffer htmlString=new StringBuffer();
		for (int i=0;i<conditions.length;i++){
			String temp[]=conditions[i].split("__");
			if (temp.length==2) {
				if ("c".equals(temp[0]) && StringUtil.isNotBlank(temp[1])) {
					tj += " and exists (select 1 from t_service_menu m where m.menuid=t.menuid and m.serviceid='" + temp[1] + "')";
				}
				if ("order".equals(temp[0])) {
					if ("mc".equals(temp[1])){
						px = " order by nlssort(t.menuname,'NLS_SORT=SCHINESE_PINYIN_M')";
					}else{
						px = " order by " + temp[1]+" ";
					}

				}
				if ("sorting".equals(temp[0])) {
					pxfs = temp[1];
				}
			}
		}
		if (StringUtil.isNotBlank(gjz)){
			tj += " and t.menuname like '%"+gjz+"%'";
		}
		if (user!=null&&!"admin".equals(user.getUserloginid())) {
			tj +=     "      and  exists" +
					"          (select 1" +
					"           from t_sys_menu m" +
					"           where m.bizcode = t.bizcode" +
					"           and m.menuid in" +
					"               (select m.menuid" +
					"                  from t_sys_role_menu m" +
					"                 where m.roleid in" +
					"                       (select ur.roleid " +
					"                        from t_sys_user_role ur" +
					"                        where ur.userid in (select u.userid " +
					" 													from t_sys_user u " +
					" 													where u.userloginid = '" + user.getUserloginid() + "'))))";
		}
		String sql=sql_serach+tj+px+pxfs;
		List<TSysMenu> menus= DBUtil.queryAllBeanList(sql, TSysMenu.class);
		htmlString.append("<ul class='ly-clearFix'>");
		if (menus!=null&&menus.size()>0) {
			for (int menus_n = 0; menus_n < menus.size(); menus_n++) {
				TSysMenu tsysmenu =menus.get(menus_n);
				htmlString.append("<li>");
				htmlString.append("<div class='image' onclick=\"window.open('"+path+"/s/shd/fwdh/details/"+tsysmenu.getMenuid()+"');\">");
				htmlString.append("<i class=''></i>");
				htmlString.append("<img src='"+path+"/resources/images/shd/index/icon/"+(rand.nextInt(11)+1)+".png'>");
				htmlString.append("</div>");
				htmlString.append("<div class='information' onclick=\"window.open('"+path+"/s/shd/fwdh/details/"+tsysmenu.getMenuid()+"');\">");
				htmlString.append("<div style='overflow: hidden'>");
				htmlString.append("<div class='title fontYH tl' title="+tsysmenu.getMenuname()+">"+tsysmenu.getMenuname()+"</div>");
				htmlString.append("<i class=''></i>");
				htmlString.append("</div>");
				htmlString.append("<div class='classify fontYH tl' title='"+tsysmenu.getFwtype()+"'>"+tsysmenu.getFwtype()+"</div>");
				htmlString.append("</div>");
				htmlString.append("<div class='informationxx'>");
				htmlString.append("<div class=\"alines\">");
				htmlString.append("<label>发布单位：</label><span title='"+tsysmenu.getUnit()+"'>"+tsysmenu.getUnit()+"</span></div>");
				htmlString.append("<div class=\"alines\">");
				htmlString.append("<label>办理时间：</label><span title='"+tsysmenu.getWorkingtime()+"'>"+tsysmenu.getWorkingtime()+"</span></div>");
				htmlString.append("<div class=\"alines\">");
				htmlString.append("<label>办理地点：</label><span title='"+tsysmenu.getWorkingplace()+"'>"+tsysmenu.getWorkingplace()+"</span></div>");
				htmlString.append("<div class=\"alines\">");
				htmlString.append("<label>联系方式：</label><span title='"+tsysmenu.getContact()+"'>"+tsysmenu.getContact()+"</span></div>");
				htmlString.append("<div class=\"alines\">");
				htmlString.append("<label>满意度：</label><span class='star' data-score='"+tsysmenu.getScore()+"' data-readOnly='true' style='height: 16px;line-height: 16px;text-align: center'></span></div>");
				htmlString.append("<div class='collection'>");
				htmlString.append("<div onclick=\"add_service('"+tsysmenu.getMenuid()+"')\">");
				htmlString.append("<img src='"+path+"/resources/images/shd/index/star.png' width='23' height='40' alt='' /><span>收藏</span></div>");
				htmlString.append("</div>");
				htmlString.append("</div>");
				htmlString.append("</li>");
			}
		}
		htmlString.append("</ul>");
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(htmlString.toString());
		out.flush();
		out.close();
	}
}
